import {refreshToken} from './auth'

// const apiHost = 'http://192.168.51.85:9099'
const apiHost = 'http://8.137.95.150:9000'

let isRefreshing = true;
let subscribers = [];

function onAccessTokenFetched() {
    subscribers.forEach((callback) => {
        callback();
    })
    subscribers = [];
}

function addSubscriber(callback) {
    subscribers.push(callback)
}

const getNewToken = () => {
    return new Promise((resolve, reject) => {
        const rtoken = uni.getStorageSync('refreshToken')
        refreshToken({
            refreshToken:rtoken
        }).then(result => {
            console.info('-------调用登录接口-------',result)
            uni.setStorageSync('token', result.data.accessToken)
            uni.setStorageSync('refreshToken', result.data.refreshToken)
            uni.setStorageSync('userId', result.data.userId)
            resolve(result.data.accessToken)
        })
    })
}

const httpRequest = ({ url, method, data, isTest = false, callback = '' }) => {
    // 全局携带请求参数
    let ios = 0
    const systemInfo = uni.getSystemInfoSync()
    var osName = systemInfo.osName;
    if (osName == 'ios') {
        ios = 1
    } else {
        ios = 0
    }
    let header = {}
    const token = uni.getStorageSync('token')
    if (token) {
        header['Authorization'] = 'Bearer ' + token
    }
    // 
    header['x-user-group'] = 'client_user'
    let httpDefaultOpts = {
        header: header,
        url: apiHost + url,
        data,
        method,
        beforeSend: function (xmlHttp) {
            xmlHttp.setRequestHeader("If-Modified-Since", "0");
            xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        },
        dataType: 'json',
    }
    let promise = new Promise(function (resolve, reject) {
        uni.request(httpDefaultOpts).then(
            (res) => {
                if (callback) return callback(res.data)
                const { code, msg } = res.data
                if (code === 401) {
                    addSubscriber(() => {
                        httpRequest({ url, method, data, isTest, callback: resolve })
                    })
                    if (isRefreshing) {
                        getNewToken().then(() => {
                            onAccessTokenFetched();
                            isRefreshing = true;
                        })
                    }
                    isRefreshing = false;
                } else {
                    if(code == 200){
                        resolve(res.data)
                    }else{
                        uni.showToast({
                            icon: 'none',
                            title: msg || '网络异常，请检查网络状态',
                            duration: 3000
                        })
                        reject(res.data)
                    }
                }
            }
        ).catch(
            (response) => {
                uni.showToast({
                    icon: 'none',
                    title: response?.msg || '网络异常，请检查网络状态',
                    duration: 3000
                })
                reject(response)
            }
        )
    })
    return promise
}

export default  httpRequest